<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { GetData, PostCancelLiving, deleteLiving } from '@/api/modules/living'
import PageNumber from '@/store/modules/PageNumberCache'

// const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()
const PageNumberCache = PageNumber()

const findFrom = ref({
  Theme: '',
})
const dataList: any = reactive({
  list: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Theme && ({ Theme: findFrom.value.Theme })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 添加
function AddData() {
  router.push({
    name: 'livingDetail',
  })
}

// 编辑
function Redact(id: number) {
  router.push({
    name: 'livingDetail',
    query: {
      id,
    },
  })
}

// 编辑
function Cancel(id: number) {
  ElMessageBox.confirm(
    '你确定要取消预约直播间吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostCancelLiving({ livingid: id }).then((res: any) => {
        if (res.succeeded) {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          GetDataList(PageNumberCache.GetLivingPage(), PageSize)
        }
        else {
          ElMessage.error(`操作失败。 ${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}

function Delete(id: string) {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteLiving(id).then((res: any) => {
        if (res.succeeded) {
          GetDataList(PageNumberCache.GetLivingPage(), PageSize)
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
        else {
          ElMessage.error(`删除失败${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 图片预览
const srcList = ref([])

function handlePreview(row: any) {
  srcList.value = row.activityDetailImageList.map((url: string) => url)
}

// 详情
const EveryDetails = ref<any>({})
const viewDetailsDialog = ref(false)
function ViewDetails(row: any) {
  EveryDetails.value = { ...row.livingInfo }
  viewDetailsDialog.value = true
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNumberCache.SetLivingPage(val)
}

const nowPageNum = computed(() => {
  return PageNumberCache.GetLivingPage()
})

onMounted(async () => {
  GetDataList(PageNumberCache.GetLivingPage(), 20)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="直播标题">
                <el-input v-model="findFrom.Theme" placeholder="请输入直播标题" clearable @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="livingid" label="直播ID" width="320" />
        <el-table-column header-align="center" prop="livingInfo.theme" label="直播标题" width="220" />
        <el-table-column align="center" prop="activityCoverMediaurl" label="直播间封面图" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="scope.row.activityCoverMediaurl" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="activityShareMediaurl" label="直播分享卡片图" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src=" scope.row.activityShareMediaurl" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag>
              {{ scope.row.status === 0 ? '预约中'
                : scope.row.status === 1 ? '直播中'
                  : scope.row.status === 2 ? '已结束' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="livingStartTime" label="开始时间" width="200" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
        <el-table-column align="center" prop="activityDetailImageList" label="评测图片" width="500">
          <template #default="scope">
            <el-scrollbar>
              <div class="scrollbar-flex-content">
                <el-image
                  v-for="(item, index) in scope.row.activityDetailImageList"
                  :key="index"
                  class="scrollbar-flex-img"
                  :src="item"
                  :preview-src-list="srcList"
                  :initial-index="index"
                  :preview-teleported="true"
                  @click="handlePreview(scope.row)"
                />
              </div>
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="260">
          <template #default="scope">
            <div class="table-button">
              <el-button @click="ViewDetails(scope.row)">
                详情
              </el-button>
              <el-button v-if="scope.row.status !== 4" type="primary" @click="Redact(scope.row.livingid)">
                更新
              </el-button>
              <el-button v-if="scope.row.status !== 4" type="warning" @click="Cancel(scope.row.livingid)">
                取消
              </el-button>
              <el-button type="danger" @click="Delete(scope.row.id)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog v-model="viewDetailsDialog" title="详细信息" width="1200">
      <el-descriptions border :column="4">
        <el-descriptions-item label="发起者UserId">
          {{ EveryDetails.anchor_userid }}
        </el-descriptions-item>
        <el-descriptions-item label="直播标题">
          {{ EveryDetails.theme }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ dayjs.unix(EveryDetails.living_start).format('YYYY-MM-DD HH:mm:ss') }}
        </el-descriptions-item>
        <el-descriptions-item label="直播持续时长(秒数)">
          {{ EveryDetails.living_duration }}
        </el-descriptions-item>
        <el-descriptions-item label="直播简介">
          {{ EveryDetails.description }}
        </el-descriptions-item>
        <el-descriptions-item label="直播类型">
          {{ EveryDetails.type === 0 ? '通用直播'
            : EveryDetails.type === 1 ? '小班课'
              : EveryDetails.type === 2 ? '大班课'
                : EveryDetails.type === 3 ? '企业培训'
                  : EveryDetails.type === 4 ? '活动直播' : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="agentid">
          {{ EveryDetails.agentid }}
        </el-descriptions-item>
        <el-descriptions-item label="提醒时间(秒数)">
          {{ EveryDetails.remind_time }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="viewDetailsDialog = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: auto;
    margin-right: 10px;
  }
}

.table-button {
  line-height: 42px;
}
</style>
